package com.example.common.networkutil

import com.example.common.tools.LogUtils
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okio.Buffer
import retrofit2.Converter
import java.io.OutputStreamWriter
import java.io.Writer
import java.nio.charset.Charset

class MyRequestBodyConverter<T> : Converter<T, RequestBody> {

    companion object {
        private val MEDIA_TYPE: MediaType = "application/json; charset=UTF-8".toMediaType()
        private val UTF_8 = Charset.forName("UTF-8")
    }

    private var gson: Gson? = null
    private var adapter: TypeAdapter<T>? = null

    constructor(gson: Gson, adapter: TypeAdapter<T>){
        this.adapter = adapter
        this.gson = gson
    }

    override fun convert(value: T): RequestBody? {
        val buffer = Buffer()
        val writer: Writer = OutputStreamWriter(buffer.outputStream(), UTF_8)
        val jsonWriter = gson!!.newJsonWriter(writer)
        adapter!!.write(jsonWriter, value)
        jsonWriter.close()
        var jsonString = RequestBody.create(MEDIA_TYPE, buffer.readByteString())
        LogUtils.eLog("http","Request请求数据 ----------》  $jsonString")
        return jsonString
    }
}

